package com.hontech.desktoppastacooker.ui.activity


import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.hontech.desktoppastacooker.R
import com.hontech.desktoppastacooker.ui.fragment.*
import com.hontech.desktoppastacooker.utils.dimenById
import com.hontech.desktoppastacooker.utils.log


class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Delegate(this)
        val w = resources.displayMetrics.widthPixels
        val h = resources.displayMetrics.heightPixels
        log("w:$w h :$h ${dimenById(R.dimen.test)}")
    }
}

private class Delegate(activity: BaseActivity) : FragmentStateAdapter(activity) {

    private class TabInfo(
        val text: String,
        val iconId: Int,
        val fragment: Fragment
    )

    private val vp2 = activity.findViewById<ViewPager2>(R.id.id_main_vp2)
    private val tabLayout = activity.findViewById<TabLayout>(R.id.id_main_tab_layout)

    private val tabs = arrayOf(
        TabInfo("设置", R.drawable.ic_setting_n, SettingFragment()),
        TabInfo("设置1", R.drawable.ic_test, Test1Fragment()),
        TabInfo("测试2", R.drawable.ic_test, Test2Fragment()),
        TabInfo("煮面", R.drawable.ic_cooking, CookingFragment()),
        TabInfo("RFID", R.drawable.ic_rfid, RfidFragment())
    )

    init {
        vp2.adapter = this
        vp2.offscreenPageLimit = tabs.size
        TabLayoutMediator(tabLayout, vp2) { tab, position ->
            tab.text = tabs[position].text
            tab.setIcon( tabs[position].iconId )
        }.attach()
    }

    override fun getItemCount(): Int {
        return tabs.size
    }

    override fun createFragment(position: Int): Fragment {
        return tabs[position].fragment
    }

}
